import uuid
from typing import Optional

from fastapi import APIRouter, Body
from pydantic import BaseModel, Field

from app.core.chains import get_rag_chain
from app.core.memory.memory_manager import get_session_history


router = APIRouter()


class KBChatRequest(BaseModel):
    query: str = Field(..., description="User's question for the knowledge base.")
    conversation_id: Optional[str] = Field(None,
                                           description="A unique ID for the conversation. If not provided, a new one will be generated.")
    style: Optional[str] = Field(None,description="The style of the response.")


class KBChatResponse(BaseModel):
    answer: str
    conversation_id: str


@router.post("/", response_model=KBChatResponse)
def knowledge_base_chat(request: KBChatRequest = Body(...)):
    """
    Handles a stateful chat request against the knowledge base.
    Uses conversation_id to maintain context.
    """
    conv_id = request.conversation_id or str(uuid.uuid4())
    print(f"--- KB Chat endpoint called for conversation_id: {conv_id} ---")

    chat_history_backend = get_session_history(conv_id)
    rag_chain = get_rag_chain()

    result = rag_chain.invoke({
        "input": request.query,
        "chat_history": chat_history_backend.messages
    })

    answer = result.get("answer", "I'm sorry, I couldn't find an answer.")

    # 验证风格（调试阶段使用）
    if not validate_style_response(answer, request.style):
        print(f"警告：回答不符合 {request.style} 风格要求！")
        # 可以选择重新生成回答或添加风格修正指令

    chat_history_backend.add_user_message(request.query)
    chat_history_backend.add_ai_message(answer)

    return KBChatResponse(
        answer=answer,
        conversation_id=conv_id
    )


def validate_style_response(answer: str, style: str) -> bool:
    """简单验证回答是否符合风格要求"""
    if not style:
        return True

    if style == "concise":
        return len(answer.splitlines()) <= 3 and len(answer) <= 150

    if style == "detailed":
        return "【准备】" in answer and "【步骤】" in answer and "【注意】" in answer

    if style == "humorous":
        return any(
            梗 in answer
            for 梗 in ["向导", "克苏鲁", "史莱姆", "砸了", "去世", "嘲笑"]
        )

    if style == "professional":
        # 检查是否包含至少3个游戏机制术语
        terms = ["NPC AI", "碰撞箱", "伤害类型", "合成路径", "刷新机制"]
        return sum(term in answer for term in terms) >= 3

    return True
